<?php

declare (strict_types=1);

namespace app\store\controller\market;

use app\common\model\ExchangeLog as ExchangeLogModel;
use think\response\Json;
use app\store\controller\Controller;
use app\store\model\Exchange as ExchangeModel;


/**
 * 兑换码库管理
 * Class Coupon
 * @package app\store\controller\market
 */
class Exchange extends Controller
{
    /**
     * 列表记录
     * @return Json
     * @throws \think\db\exception\DbException
     */
    public function list(): Json
    {
        $model = new ExchangeModel();
        $list = $model->getList($this->request->param());
        return $this->renderSuccess(compact('list'));
    }

    /**
     * 详情记录
     * @param int $couponId
     * @return Json
     */
    public function detail(int $couponId): Json
    {
        $detail = ExchangeModel::detail($couponId);
        return $this->renderSuccess(compact('detail'));
    }

    /**
     * 添加兑换码库
     * @return Json
     */
    public function add(): Json
    {
        // 新增记录
        $model = new ExchangeModel;
        if ($model->add($this->postForm())) {
            return $this->renderSuccess('添加成功');
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 更新兑换码库
     * @param int $couponId
     * @return Json
     */
    public function edit(int $couponId): Json
    {
        // 兑换码库详情
        $model = ExchangeModel::detail($couponId);
        // 更新记录
        if ($model->edit($this->postForm())) {
            return $this->renderSuccess('更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 删除兑换码库
     * @param int $exchangeId
     * @return Json
     */
    public function delete(int $exchangeId): Json
    {
        // 兑换码库详情
        $model = ExchangeModel::detail($exchangeId);
        // 更新记录
        if ($model->delete()) {
            return $this->renderSuccess('删除成功');
        }
        return $this->renderError($model->getError() ?: '删除成功');
    }

    public function getExchangeLog():Json{
        $model = new ExchangeLogModel();
        $list = $model->alias("log")
            ->join("user","log.user_id = user.user_id")
            ->join("exchange_code code","log.code_id = code.id")
            ->field("log.id,code.code,user.nick_name,user.mobile,log.createtime")
            ->paginate(10);
        return $this->renderSuccess(compact("list"));
    }

}
